package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pojo.Order;


public class ShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");

		HttpSession session = request.getSession();
		String itemName = request.getParameter("name");
		String name = new String(itemName.getBytes("ISO-8859-1"), "UTF-8");
		String price = request.getParameter("price");
		String amount = request.getParameter("amount");
		request.getSession().getAttribute("orderList");

		System.out.println(name);
		
		List<Order> orderList = (List<Order>)session.getAttribute("orderList");
		if(orderList == null){
			orderList = new ArrayList<Order>();
		}

		Order order = new Order(name, Double.parseDouble(price), Integer.parseInt(amount));

		boolean addOrderFlag = true;
		for(int i = 0; i < orderList.size(); i++){
			if (orderList.get(i).getName().equals(order.getName())){
				orderList.get(i).setAmount(Integer.parseInt(amount));
				orderList.get(i).setPrice(Double.parseDouble(price));
				addOrderFlag = false;
			}
		}
		if (addOrderFlag){
			orderList.add(order);
		}

		session.setAttribute("orderList", orderList);
	}

}
